﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Runtime.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DragDropTest;

namespace FileUploader
{
    public class DataPersister
    {
        private const string fileName = "DemoData.xml";

        public static void WriteData(ObservableCollection<DemoData> dataToSave)
        {
            DemoDataCollection dataCollection = new DemoDataCollection(dataToSave);
            MemoryStream memoryStream = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(typeof(DemoDataCollection));
            serializer.WriteObject(memoryStream, dataCollection);

            byte[] stuff = memoryStream.ToArray();
            string value = Encoding.UTF8.GetString(stuff, 0, stuff.Length);

            using (var store = IsolatedStorageFile.GetUserStoreForSite())
            {

                if (store.FileExists(fileName))
                {
                    store.DeleteFile(fileName);
                }

                using (var outputStream = store.CreateFile(fileName))
                {
                    outputStream.Write(stuff, 0, stuff.Length);
                };



            }
        }


        public static ObservableCollection<DemoData> ReadData()
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(DemoDataCollection));
            DemoDataCollection newList;
            using (var store = IsolatedStorageFile.GetUserStoreForSite()){
                using (var inputStream = store.OpenFile(fileName, FileMode.OpenOrCreate))
                {
                    if(inputStream.Length==0){return new ObservableCollection<DemoData>();}
                    newList = (DemoDataCollection)serializer.ReadObject(inputStream);

                }
            }
            return newList != null  && newList.Items != null ? newList.Items : new ObservableCollection<DemoData>();
        }


    }
}
